package start.spring.basic.job.job;

import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.PreDestroy;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;
import start.spring.basic.exception.ExceptionUtil;
import start.spring.basic.job.job.jobthread.DemoThread;
import start.spring.basic.job.quartz.QuartzConstant;
import start.spring.basic.job.service.demo.IDemoService;
import start.spring.basic.log.LogConstant;

/**
 * 
 * ****************************************************************************
 * 自动任务样例
 * 此demo任务并行调度，业务逻辑内部保证任务的串行执行。适用于多线程处理业务的情况。
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2021年5月7日
 ******************************************************************************
 */
@Slf4j
public class DemoJob extends BaseJob implements Job {
	
	private String className = getClass().getName();
	
	private static ThreadPoolExecutor cachedThreadPool = null;
    private final String threadName = "自动任务多线程样例线程";
	
	@Autowired
	IDemoService demoService;

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		String errMsg = "";
		
		try {
			//任务已经执行完毕
			if(super.jobCanExcute(className,context)) {
				//修改自动任务开始执行
				super.reJobStart(className);
				
				int threadNum = super.getThreadNum(context);
				if (cachedThreadPool == null) {
					cachedThreadPool = super.getThreadPool(threadName,threadNum);
		        }
				
				for(int i=0;i<threadNum;i++) {
					
					DemoThread dt = new DemoThread();
					dt.setThreadName(threadName + "-" + (i+1));
					dt.setThreadCount(threadNum);
					dt.setThreadXh(i+1);
					dt.setPch(MDC.get(LogConstant.REQUEST_KEY_TRACEID).toString());
					dt.setJobClassName(className);
					dt.setJobService(jobService);
					
					dt.setDemoService(demoService);
					
					cachedThreadPool.execute(dt);
				}
			}
			
		}catch(Exception e) {
			errMsg = ExceptionUtil.getExceptionDeteil(e, 0);
			log.error("",e);
			
			//记录任务执行失败日志
			super.reJobEnd(QuartzConstant.JOB_STATUS_FAIL, errMsg, className);
		}
	}
	
	@PreDestroy
    public void destroyBean() {
        if (cachedThreadPool != null) {
            cachedThreadPool.shutdownNow();
        }
    }
	
}
